<!-- 添加编辑金融产品 -->
<template>
  <el-dialog
    :title="title"
    :visible.sync="show"
    width="500px"
    @close="$emit('update:visible', false)"
    class="add-list-dialog"
  >
    <el-form
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="left"
      ref="accounForm"
      size="small"
      width="300px;"
    >
      <el-form-item label="产品类型：" prop="productType">
        <el-select
          v-model.trim="form.productType"
          :disabled="editDisabled"
          :clearable="true"
          placeholder="请选择"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="授信额度：" prop="lineofCredit">
        <div class="flex-box">
          <el-input-number
            :min="inputNumber.min"
            :max="inputNumber.max"
            :step="inputNumber.step"
            v-model="form.lineofCredit"
          ></el-input-number>
          <div>元</div>
        </div>
      </el-form-item>
      <div class="form-line"></div>
      <el-form-item label="资金方：" prop="selectParty">
        <el-checkbox-group v-model="selectPartyArray" :disabled="editCreditDisabled">
          <div class="flex-box f-column">
            <el-checkbox
              :label="id"
              v-for="({fundSideName,lineofCredit,interestRate,id},idx) in partyFunds"
              :key="idx"
              @change="checkChange(id,selectPartyArray.includes(id))"
              name="selectParty"
            >
              <div class="flex-box">
                <div class="check-label">{{fundSideName}}</div>
                <div
                  class="flex-item"
                  v-show="selectPartyArray.includes(id)"
                >可用额度：{{allUsdMap[id]||lineofCredit}}</div>
                <div class="f-txr" v-show="selectPartyArray.includes(id)">{{interestRate}}%</div>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        :label="partyFunds.find(item=>item.id == id).fundSideName + '分担：'"
        :prop="`productInfos.${idx}.sharedQuota`"
        :rules="rules.share"
        v-for="(id,idx) in selectPartyArray"
        :key="idx"
      >
        <div class="flex-box">
          <el-input-number
            :min="0"
            :max="form.productInfos[idx].lineofCredit"
            :step="inputNumber.step"
            :disabled="selectPartyArray.length == 1 "
            v-model="form.productInfos[idx].sharedQuota"
          ></el-input-number>
          <div>元</div>
        </div>
      </el-form-item>
      <div class="form-line"></div>
      <el-form-item label="成本风控：" prop="cost">
        <div class="flex-box">
          <el-input
            :disabled="editCreditDisabled"
            v-model.trim="form.beginCostControl"
            autocomplete="off"
          >
            <template slot="append">%</template>
          </el-input>
          <span>——</span>
          <el-input
            :disabled="editCreditDisabled"
            v-model.trim="form.endCostControl"
            autocomplete="off"
          >
            <template slot="append">%</template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="可用周期：" prop="cycle">
        <div class="flex-box">
          <el-input
            :disabled="editCreditDisabled"
            v-model.trim="form.beginCycle"
            autocomplete="off"
          >
            <template slot="append">天</template>
          </el-input>
          <span>——</span>
          <el-input :disabled="editCreditDisabled" v-model.trim="form.endCycle" autocomplete="off">
            <template slot="append">天</template>
          </el-input>
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="save('accounForm')">确 定</el-button>
    </template>
  </el-dialog>
</template>
<script>
import api from "@/api/apiPath";
export default {
  computed: {
    editDisabled() {
      return this.type === "edit";
    },
    //编辑时 ，已拆解资金为0时 只可编辑额度；
    editCreditDisabled() {
      return this.type === "edit" && this.form.dismantledCapital !== 0;
    },
    lineofCredit() {
      return this.form.lineofCredit;
    }
  },
  data() {
    return {
      inputNumber: {
        max: 999999999999.99,
        min: 10000,
        step: 10000
      },
      form: {
        productType: 1,
        lineofCredit: "",
        beginCostControl: "",
        endCostControl: "",
        beginCycle: "",
        endCycle: "",
        productInfos: []
      },
      title: "新增",
      show: false,
      typeOptions: [{ label: "佣金垫付", value: 1 }],
      selectPartyArray: [],
      allUsdMap: {}, //已使用数和可用数之和，id为key
      rules: {
        cost: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              let res = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
              let begin = this.form.beginCostControl;
              let end = this.form.endCostControl;
              if (begin <= 0 || end <= 0) {
                return callback(new Error("只能为正数"));
              }
              if (!begin || !end) {
                return callback(new Error("请输入成本风控"));
              }

              if (!res.test(begin) || !res.test(end)) {
                return callback(new Error("格式不正确，只能保留两位小数"));
              }
              //转换为数字
              begin *= 1;
              end *= 1;
              if (end <= begin) {
                return callback(new Error("后一位必须大于前一位"));
              }
              callback();
            }
          }
        ],
        cycle: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              let res = /^[+]{0,1}(\d+)$/;
              let begin = this.form.beginCycle;
              let end = this.form.endCycle;
              let partyMinCycle = this.partyMinCycle;
              if (!begin || !end) {
                return callback(new Error("请输入可用周期"));
              }
              if (!res.test(begin) || !res.test(end)) {
                return callback(new Error("只能为正整数"));
              }
              //转换为数字
              begin *= 1;
              end *= 1;
              if (end <= begin) {
                return callback(new Error("后一位必须大于前一位"));
              }
              if (end > partyMinCycle) {
                return callback(new Error("最大不超过资金方可用周期"));
              }
              if (end > 365) {
                return callback(new Error("最大不超过365天"));
              }
              callback();
            }
          }
        ],
        selectParty: [
          {
            required: true,
            trigger: ["change"],
            validator: (rule, value, callback) => {
              if (!this.selectPartyArray.length) {
                return callback(new Error("请选择资金方"));
              }

              callback();
            }
          }
        ],
        lineofCredit: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: (rule, value, callback) => {
              let res = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
              if (!value) {
                return callback(new Error("请输入授信额度"));
              }
              if (!res.test(value)) {
                return callback(new Error("只能为数字,保留两位小数点"));
              }
              callback();
            }
          }
        ],
        share: [
          {
            required: true,
            trigger: ["blur", "change", "input"],
            validator: (rule, value, callback) => {
              let use = this.form.lineofCredit;
              let allValue = 0;
              this.form.productInfos.forEach(item => {
                allValue += item.sharedQuota;
              });
              if (this.form.productInfos.length == 1) {
                if (allValue < use) {
                  return callback(new Error("可用额度不足"));
                }
              }
              if (!value) {
                return callback(new Error("请输入分担金额"));
              }
              if (allValue != use) {
                return callback(new Error("分担金额需与授信额度相同"));
              }
              callback();
            }
          }
        ]
      }
    };
  },
  props: ["visible", "type", "editform", "partyFunds"],
  watch: {
    visible(o, n) {
      if (o) {
        this.show = true;
        this.init();
      } else {
        this.show = false;
      }
    },
    lineofCredit(value) {
      if (this.selectPartyArray.length == 1) {
        //当只选择一个资金方时，占全部资金分担
        this.form.productInfos[0].sharedQuota = value;
      }
    },
    selectPartyArray(value) {
      //当只选择一个资金方时，占全部资金分担
      let id = value[0];
      let partyMinCycleArray = [];
      if (!value.length) return;
      this.form.productInfos.map(item => {
        if (item.fundSideId == id && value.length == 1) {
          //触发分担金额金额数不足验证
          this.$nextTick(() => {
            item.sharedQuota = this.form.lineofCredit;
          });
        }
        //所有到期时间集合
        partyMinCycleArray.push(+new Date(item.cooperationEndTime));
      });
      //找到最先到期时间
      let minDate = Math.min(...partyMinCycleArray);
      //计算时间戳差
      let timeDiff = minDate - new Date().getTime();
      //计算天数差
      let partyMinCycle = Math.floor(timeDiff / (24 * 60 * 60 * 1000));
      //赋值最小天数和最大周期
      this.partyMinCycle = partyMinCycle;
      if (this.type == "add") {
        this.form.endCycle = partyMinCycle > 365 ? 365 : partyMinCycle;
      }
    }
  },
  methods: {
    checkChange(id, value) {
      let infos = this.form.productInfos;
      //筛选表单中是否有当前id的资金方信息
      let info = infos.filter(t => t.fundSideId == id);
      //筛选资金方中当前id 的资金方信息
      let partyInfos = this.partyFunds.filter(t => t.id == id);
      let partyInfo = partyInfos[0];
      //选中但未添加到表单的，添加当前资金方信息
      if (value && !info.length) {
        this.form.productInfos.push({
          sharedQuota: 0,
          fundSideName: partyInfo.fundSideName,
          fundSideId: partyInfo.id,
          lineofCredit: partyInfo.lineofCredit,
          cooperationEndTime: partyInfo.cooperationEndTime
        });
      }
      //已添加到表单但未选中，删除未选中的资金方信息
      if (!value && info && info.length) {
        info = infos.filter(t => t.fundSideId !== id);
        this.form.productInfos = info;
      }
    },
    init() {
      this.form = {
        productType: 1,
        lineofCredit: "",
        beginCostControl: "",
        endCostControl: "",
        beginCycle: "",
        endCycle: "",
        productInfos: []
      };
      this.allUsdMap = {};
      if (this.type == "edit") {
        this.title = "编辑";
        let priorForm = JSON.parse(JSON.stringify(this.editform));
        //预处理编辑数据 ，添加可使用金额和到期时间
        this.selectPartyArray = [];
        priorForm.productInfos.forEach(item => {
          let partyInfos = this.partyFunds.filter(t => t.id == item.fundSideId);
          let partyInfo = partyInfos[0];
          this.selectPartyArray.push(item.fundSideId);
          //编辑时，赋值给当前显示的资金方的可用额度等于该数据已分配额度和可用额度之和
          this.allUsdMap[partyInfo.id] =
            item.sharedQuota + partyInfo.lineofCredit;
          item = Object.assign(item, {
            lineofCredit: item.sharedQuota + partyInfo.lineofCredit,
            cooperationEndTime: partyInfo.cooperationEndTime
          });
        });
        this.form = priorForm;
      } else {
        this.title = "新增";
        this.selectPartyArray = [];
        if (this.$refs["accounForm"]) {
          this.$refs.accounForm.resetFields();
        }
      }
    },
    save(formName) {
      let _this = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          _this.$emit(
            "onSave",
            this.type,
            JSON.parse(JSON.stringify(this.form))
          );
        } else {
          return false;
        }
      });
    }
  },

  created() {},
  destroyed() {},
  filters: {}
};
</script>

<style lang="stylus" scoped>
.flex-box {
  display: flex;
}

.flex-item {
  flex: 1;
}

.f-txr {
  text-align: right;
}

.f-txc {
  text-align: center;
}

.flex-box>* {
  margin-right: 10px;
}

.flex-box>*:last-child {
  margin-right: 0;
}

.form-line {
  border-bottom: 1px solid #DCDFE6;
  margin-bottom: 20px;
}

.f-fsize {
  font-size: 14px;
}

.f-column {
  flex-direction: column;
}

.check-label {
  width: 90px;
}
</style>
<style lang="stylus">
.add-list-dialog {
  .el-checkbox {
    width: 100%;
  }

  .el-checkbox__label {
    width: 90%;
  }

  .el-input-number--small {
    width: 215px;
  }

  .el-input-group {
    width: auto;
  }
}
</style>
